﻿using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for PictureViewer.xaml
    /// </summary>
    public partial class PictureViewer : Window
    {
        public string PictureSource
        {
            get { return (string)GetValue(PictureSourceProperty); }
            set { SetValue(PictureSourceProperty, value); }
        }

        bool IsPictureLoaded = false;
        // Using a DependencyProperty as the backing store for PictureSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PictureSourceProperty =
            DependencyProperty.Register("PictureSource", typeof(string), typeof(PictureViewer), new UIPropertyMetadata(string.Empty));

        //delTa值 
        private static double delTa = 1;
        //缩放的增量值 
        private static double flag = 0.5;
        private double left;
        private double top;
        private double pX;
        private double pY;
        bool IsMouseDown;
        public PictureViewer()
        {
            DataContext = this;
            
            InitializeComponent();

#if DEBUG
            Debug.Print("this.left:" + this.left);
            Debug.Print("this.top:" + this.Top);
#endif
            this.Left = SystemParameters.WorkArea.Width / 2 - this.Width / 2;
            this.Top = SystemParameters.WorkArea.Height / 2 - this.Height / 2;

            Debug.Print("1st time: this.left:" + this.Left);
            Debug.Print("1st time: this.top:" + this.Top);
        }


        private void Close(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void myImage_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                //放大
                delTa += flag;
            }
            else
            {
                //缩小
                if (delTa > flag)
                    delTa -= flag;
            }
            imgScaleTransform.ScaleX = imgScaleTransform.ScaleY = delTa;
        }

        private void window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            IsMouseDown = false;
        }

        private void myImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            IsMouseDown = true;
            Point position = e.GetPosition(this);

            left = double.Parse(myImage.GetValue(Canvas.LeftProperty).ToString());
            top = double.Parse(myImage.GetValue(Canvas.TopProperty).ToString());
            pX = position.X;
            pY = position.Y;
        }

        private void myImage_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsMouseDown)
            {
                Point position = e.GetPosition(this);
                double curX = position.X;
                double curY = position.Y;

                myImage.SetValue(Canvas.LeftProperty, left + curX - pX);
                myImage.SetValue(Canvas.TopProperty, top + curY - pY);
            }
        }
 

        private void myImage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (this.myImage.ActualHeight != 1)
            {
                double left = SystemParameters.WorkArea.Width / 2 - this.myImage.ActualWidth / 2; ;
                double top =SystemParameters.WorkArea.Height / 2 - this.myImage.ActualHeight / 2;
                this.Left = left>=0?left:0;
                this.Top = top >= 0 ? top : 0;
            }

            Debug.Print("this.myImage.ActualHeight" + this.myImage.ActualHeight);
            Debug.Print("this.myImage.ActualWidth:" + this.myImage.ActualWidth);
        }

        private void window_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape || e.Key == Key.C)
            {
                this.Close();
            }
            else if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.S)
            {
                SavePicture();
            }
        }

        private void myImage_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            double left = double.Parse(myImage.GetValue(Canvas.LeftProperty).ToString());
            double top = double.Parse(myImage.GetValue(Canvas.TopProperty).ToString());
            if (e.Key == Key.Left)
            {
                left -= 3;
            }
            else if (e.Key == Key.Right)
            {
                left += 3;
            }
            else if (e.Key == Key.Up)
            {
                top -= 3;
            }
            else if (e.Key == Key.Down)
            {
                top += 3;
            }

            myImage.SetValue(Canvas.LeftProperty, left);
            myImage.SetValue(Canvas.TopProperty, top);
        }

        private void Canvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!(e.Source.GetType() == typeof(TextBlock) || e.Source.GetType() == typeof(Rabbit.Controls.ImageEx)))
            {
                this.DragMove();
            }
        }

        private void ZoomIn_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            imgScaleTransform.ScaleX += 0.1;
            imgScaleTransform.ScaleY += 0.1;
        }

        private void ZoomOut_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (imgScaleTransform.ScaleX > 0.5)
            {
                imgScaleTransform.ScaleX -= 0.1;
                imgScaleTransform.ScaleY -= 0.1;
            }
        }

        private void LeftRotation_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            imgRotateTransform.Angle -= 90;
        }

        private void RightRotation_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            imgRotateTransform.Angle += 90;
        }

        private void Recover_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ResetPicture();
        }
        private void ResetPicture()
        {
            imgScaleTransform.ScaleX = 1;
            imgScaleTransform.ScaleY = 1;
            imgRotateTransform.Angle = 0;
            myImage.SetValue(Canvas.LeftProperty, 0.0);
            myImage.SetValue(Canvas.TopProperty, 0.0);
        }
        private void Save_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SavePicture();
        }

        private void SavePicture()
        {
            if (!IsPictureLoaded)
            {
                return;
            }

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            string ext = this.myImage.Source.Substring(this.myImage.Source.LastIndexOf('.'));
            dlg.DefaultExt = ext;
            dlg.Filter = "图片文件|" + ext;
            dlg.OverwritePrompt = true;
            bool result = dlg.ShowDialog().Value;
            if (result == true)
            {
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)myImage.ActualWidth, (int)myImage.ActualHeight, 0, 0, PixelFormats.Default);
                rtb.Render(this.myImage);
                BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                System.IO.Stream io = File.OpenWrite(dlg.FileName);
                encoder.Save(io);
                io.Close();
            }
        }



        private void window_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ResetPicture();
        }

        private void myImage_ImageLoaded(object sender, RoutedEventArgs e)
        {
            IsPictureLoaded = true;
            LoadingBorder.Visibility = Visibility.Collapsed;
        }
    }
}
